package com.flaskpy.web.eternity.auth.jwt.service.impl;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.flaskpy.web.eternity.auth.jwt.config.JwtConfigProperties;
import com.flaskpy.web.eternity.auth.jwt.context.JwtContextHolder;
import com.flaskpy.web.eternity.auth.jwt.entiry.JwtPayLoad;
import com.flaskpy.web.eternity.auth.jwt.service.IOnLineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;

/**
 * @className: DefaultOnLineService
 * @description: 这个人很赖不留下一点说明
 * @author: flaskpy 代码copy大师
 * @date: 2021/6/9
 **/
@Slf4j
public class DefaultOnLineServiceImpl implements IOnLineService, InitializingBean {
    @Autowired
    private JwtConfigProperties configProperties;

    private TimedCache<String, Object> cache;
    @Override
    public void afterPropertiesSet() throws Exception {
        log.warn("默认的在线用户服务可能不符合你的口味");
        this.cache= CacheUtil.newTimedCache(configProperties.getRenewalTime()*1000);
        this.cache.schedulePrune(5000);
    }

    @Override
    public boolean checkNonExpires(String token){
        return this.cache.containsKey(token);
    }

    @Override
    public void renewal(String token, Authentication authentication) {
        JwtPayLoad jwtPayLoad = (JwtPayLoad) this.cache.get(token);
        if(jwtPayLoad==null)
        {
            jwtPayLoad=JwtContextHolder.currentJwtPayload();
        }
        this.cache.put(token,jwtPayLoad);
    }

    @Override
    public void logout(String token) {
        this.cache.remove(token);
    }

    @Override
    public void login(String token,  Authentication authentication) {
        JwtPayLoad jwtPayload = JwtContextHolder.currentJwtPayload();
        this.cache.put(token,jwtPayload);
    }
}
